package jp.co.neosystem.s2wg.service.flex.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jp.co.neosystem.s2wg.dto.flex.ArgsGetWorkSheet;
import jp.co.neosystem.s2wg.dto.flex.ResultGetWorkSheet;
import jp.co.neosystem.s2wg.dto.flex.WorkSheet;
import jp.co.neosystem.s2wg.entity.TblTrnWorktime;
import jp.co.neosystem.s2wg.entity.TblTrnWorktimeDetail;
import jp.co.neosystem.s2wg.service.dao.WorktimeDetailService;
import jp.co.neosystem.s2wg.service.dao.WorktimeService;
import jp.co.neosystem.s2wg.service.flex.GetWorkSheetService;
import jp.co.neosystem.s2wg.util.Const;
import jp.co.neosystem.s2wg.util.DateUtil;
import jp.co.neosystem.s2wg.util.MessageCode;
import jp.co.neosystem.s2wg.util.StatusFactory;
import jp.co.neosystem.s2wg.util.WorkSheetComparator;

import org.seasar.flex2.rpc.remoting.service.annotation.RemotingService;
import org.seasar.framework.beans.util.BeanMap;

/**
 * ワークシート取得サービスクラス。
 */
@RemotingService
public class GetWorkSheetServiceImpl implements GetWorkSheetService {

	public WorktimeService worktimeService;

	public WorktimeDetailService worktimeDetailService;

	@Override
	public ResultGetWorkSheet getWorkSheet(final ArgsGetWorkSheet args,
			final boolean isTest) {
		final ResultGetWorkSheet ret = new ResultGetWorkSheet();

		// ヘッダ情報取得
		final BeanMap condition = new BeanMap();
		condition.put("userId", args.getUserId());
		condition.put("targetYearMonth", args.getTargetYearMonth());
		final List<TblTrnWorktime> w = worktimeService
				.findByCondition(condition);
		if (w == null || w.size() != 1) {
			ret.setStatus(StatusFactory.getStatus(MessageCode.WORKSHEET_GET_NG));
			return ret;
		}

		// 明細情報取得
		condition.clear();
		condition.put("workId", w.get(0).workId);
		final List<TblTrnWorktimeDetail> wDetail = worktimeDetailService
				.findByCondition(condition);

		if (wDetail == null || wDetail.size() == 0) {
			ret.setStatus(StatusFactory.getStatus(MessageCode.WORKSHEET_GET_NG));
			return ret;
		}

		final List<WorkSheet> list = new ArrayList<WorkSheet>();
		for (final TblTrnWorktimeDetail d : wDetail) {
			final WorkSheet s = new WorkSheet();
			s.setBaseDate(DateUtil.convert(args.getTargetYearMonth(), d.day));
			s.setStartTime(d.startTime);
			s.setEndTime(d.endTime);

			if (Const.HOLIDAY_DIV_WEEKDAY.equals(d.holidayDiv)) {
				s.setIsHoliday(false);
			} else {
				s.setIsHoliday(true);
			}
			s.setWorkOption1(d.workOption1);
			s.setWorkOption2(d.workOption2);
			list.add(s);
		}
		
		Collections.sort(list, new WorkSheetComparator());
		ret.setWorkSheetList(list);
		ret.setStatus(StatusFactory.getStatus(MessageCode.WORKSHEET_GET_OK));
		return ret;
	}
}
